/**
 * 渠道发布预览-官网
 */
import React from 'react';
import { BlockTitle } from '@/molecules';
import { BottomAction } from '@/components';
import { useRequest } from '@/hooks';
import { Form, Card, Button, Input, InputNumber, Select, Radio, message, Row, Col } from 'antd';
import { dictionaryList } from '@/services/dictionary';
import { debounce } from 'lodash';
import useRecruitOutwardsChannelDetail from './useRecruitOutwardsChannelDetail';
import useRecruitOutwardsChannelUpdate from './useRecruitOutwardsChannelUpdate';
import { getOrgCity, getPositionTags } from '../../service';

const { TextArea } = Input;
const { Option } = Select;
const fetchDictValue = (dict, value) => (dict || []).find(item => item.dictValue === value)?.dictName;
const formItemLayout = {
    labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
    },
    wrapperCol: {
        xs: { span: 24 },
        sm: { span: 17 }
    }
};

const getCity = arr => {
    if (arr && arr.length > 0) {
        const temp = [];
        arr.forEach(item => {
            const area = item?.area || '';
            const tempArr = area.split(',');
            let str = '';
            if (tempArr.length > 3) {
                str = tempArr[2] === '市辖区' ? tempArr[1] : tempArr[2];
            } else if (tempArr.length > 0) {
                str = tempArr[tempArr.length - 1];
            }
            if (!temp.includes(str)) {
                temp.push(str);
            }
        });
        return temp;
    }
    return [];
};

const monthMoney = ['12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24'];
const OfficialWebsitePreviewForm = ({ form, outwardId, onSuccess, onError, channelCode }) => {
    const { getFieldDecorator, validateFields, getFieldValue } = form;
    const [dictObj, setDictObj] = React.useState(null);

    // 表单设置
    const [postData, postFetching] = useRecruitOutwardsChannelDetail(outwardId, channelCode);
    const [runSubmit, submitLoading] = useRecruitOutwardsChannelUpdate(onSuccess, onError);

    // 工作城市
    const { data: cityList, run: fetchCityList } = useRequest(getOrgCity, {
        manual: true,
        initialData: [],
        formatResult: res => {
            if (res) {
                const { code, data, msg } = res;
                if (code === 10000) {
                    return getCity(data);
                }
                message.error(msg);
            }
            return undefined;
        }
    });

    // 获取职位关键词列表
    const { data: tagList, run: fetchPositionTags } = useRequest(tagName => getPositionTags(tagName), {
        // debounceInterval: 400,
        manual: true,
        formatResult: res => {
            if (res) {
                const { code, data, msg } = res;
                if (code === 10000) {
                    return [...new Set(data || [])];
                }
                message.error(msg);
            }
            return undefined;
        }
    });

    React.useEffect(() => {
        if (!postData) {
            return;
        }

        const channelRecruitInfo = JSON.parse(postData?.channelRecruitInfo || null);
        fetchCityList(channelRecruitInfo.companyCode);
        if (!channelRecruitInfo) {
            return;
        }
        const {
            dutyName,
            workNature,
            workYears,
            recruitDegree,
            workCity,
            recruitNums,
            recruitSex,
            positionDuty,
            minSalary,
            maxSalary,
            salaryNum,
            jobRequirement,
            positionTag
        } = channelRecruitInfo;

        const finalPositionDuty = positionDuty?.replace('</br>', '\n');

        form.setFieldsValue({
            dutyName,
            recruitNums,
            recruitDegree,
            workNature,
            workYears,
            recruitSex,
            positionDuty: finalPositionDuty,
            workCity,
            minSalary,
            maxSalary,
            jobRequirement,
            salaryNum: salaryNum || undefined,
            positionTag: positionTag ? positionTag.split(',') : undefined
        });
    }, [postData]);

    // 需获取当前数据所在部门

    const fetchDictionary = async () => {
        const res = await dictionaryList({
            codes: ['jobNature', 'candidateSexType', 'agreeType', 'timeEmployedType']
        });
        const { code, data, msg } = res;
        if (code === 10000) {
            const obj = {};
            data.forEach(item => {
                if (obj[item.code]) {
                    obj[item.code].push(item);
                } else {
                    obj[item.code] = [item];
                }
            });
            setDictObj(obj);
        } else {
            message.error(msg);
        }
    };

    const handleSubmit = e => {
        e.preventDefault();
        form.validateFieldsAndScroll(async (err, values) => {
            if (err) {
                return;
            }
            const { workCity, workYears, recruitDegree, workNature, positionTag } = values;
            if (positionTag && positionTag.length > 0) {
                if (positionTag.some(tag => tag.length > 20)) {
                    message.error('单个职位关键词长度不可超过20个字符');
                    return;
                }
            }
            const channelRecruitInfo = JSON.parse(postData?.channelRecruitInfo || null);
            const finalWorkCity = Array.isArray(workCity) ? workCity.join(',') : workCity;
            const extend = {
                workCity: finalWorkCity,
                recruitDegreeName: fetchDictValue(dictObj?.agreeType, recruitDegree),
                workYearsName: fetchDictValue(dictObj?.timeEmployedType, workYears),
                workNatureName: fetchDictValue(dictObj?.jobNature, workNature),
                positionTag: positionTag && positionTag.length > 0 ? positionTag.join(',') : ''
            };
            runSubmit(outwardId, channelCode, JSON.stringify({ ...channelRecruitInfo, ...values, ...extend }));
        });
    };

    React.useEffect(() => {
        fetchDictionary();
    }, []);

    const renderOptions = arr => {
        if (arr && arr.length > 0) {
            return arr.map(item => (
                <Option value={item.dictValue} key={item.dictValue}>
                    {item.dictName}
                </Option>
            ));
        }
        return null;
    };

    const renderOptionsMonth = arr => {
        if (arr && arr.length > 0) {
            return arr.map(item => (
                <Option value={item} key={item}>
                    {item}
                </Option>
            ));
        }
        return null;
    };

    const renderRadios = arr => {
        if (arr && arr.length > 0) {
            return arr.map(item => (
                <Radio value={item.dictValue} key={item.dictValue}>
                    {item.dictName}
                </Radio>
            ));
        }
        return null;
    };

    const handleForceValidate = keys => {
        validateFields(keys, { force: true });
    };
    React.useEffect(() => {
        handleForceValidate(['temp']);
    }, [getFieldValue('minSalary'), getFieldValue('maxSalary')]);
    const checkPrice = (rule, value, callback) => {
        const from = getFieldValue('minSalary');
        const to = getFieldValue('maxSalary');
        if (!from || !to) {
            return callback('请输入薪资范围');
        }
        if (from - to > 0) {
            return callback('薪资最小值不能大于最大值');
        }
        return callback();
    };
    const renderSalaryForm = () =>
        getFieldDecorator('temp', {
            initialValue: 1,
            rules: [{ required: true, message: '\r' }, { validator: checkPrice }]
        })(
            <div style={{ display: 'flex', width: '55%' }}>
                <Form.Item label="" colon={false} style={{ width: '33%', marginBottom: 0 }}>
                    {getFieldDecorator('minSalary', {
                        rules: [
                            {
                                required: true,
                                message: '不能为空'
                            }
                        ]
                    })(<InputNumber placeholder="请输入" precision={0} min={0} style={{ width: '100%' }} />)}
                </Form.Item>
                <span style={{ padding: '0 8px' }}>K</span>
                <span style={{ margin: '0 8px' }}>~</span>
                <Form.Item label="" colon={false} style={{ width: '33%', marginBottom: 0 }}>
                    {getFieldDecorator('maxSalary', {
                        rules: [
                            {
                                required: true,
                                message: '不能为空'
                            }
                        ]
                    })(<InputNumber placeholder="请输入" precision={0} min={0} style={{ width: '100%' }} />)}
                </Form.Item>
                <span style={{ padding: '0 8px' }}>K</span>
                <span style={{ margin: '0 8px' }}>*</span>
                <Form.Item label="" colon={false} style={{ width: '30%', marginBottom: 0 }}>
                    {getFieldDecorator('salaryNum', {
                        rules: [
                            {
                                required: true,
                                message: '不能为空'
                            }
                        ]
                    })(
                        <Select placeholder="请选择" allowClear style={{ width: '100%' }}>
                            {renderOptionsMonth(monthMoney)}
                        </Select>
                    )}
                </Form.Item>
                <Form.Item label="" colon={false} style={{ marginLeft: 10 }}>
                    {postData?.companyCurrencyCode || '薪'}
                </Form.Item>
            </div>
        );

    const handleTagChange = () => {
        fetchPositionTags('');
    };

    const handleTagSearch = debounce(value => {
        fetchPositionTags(value?.trim() || '');
    }, 400);

    return (
        <Card
            bordered={false}
            title={<div style={{ margin: '10px 0' }}>渠道发布信息</div>}
            loading={postFetching}
            extra={postData?.channelLogoUrl && <img height="44" src={postData?.channelLogoUrl || ''} alt="官网" />}
        >
            <BottomAction>
                {/* <Button onClick={() => pageTabUtil.goBack()} style={{ marginRight: 8 }}>
                            取消
                        </Button> */}
                <Button type="primary" onClick={handleSubmit} loading={submitLoading}>
                    提交
                </Button>
            </BottomAction>
            <BlockTitle title="基本信息" style={{ marginBottom: 24 }} />
            <Form {...formItemLayout}>
                <Form.Item label="岗位名称">
                    {getFieldDecorator('dutyName', {
                        rules: [
                            {
                                required: true,
                                message: '岗位名称不能为空',
                                whitespace: true
                            }
                        ]
                    })(<Input placeholder="请输入岗位名称" style={{ width: '55%' }} />)}
                </Form.Item>
                <Form.Item label="招聘人数">
                    {getFieldDecorator('recruitNums', {
                        rules: [
                            {
                                required: true,
                                message: '请输入招聘人数'
                            }
                        ]
                    })(
                        <InputNumber
                            style={{ width: '55%' }}
                            min={0}
                            max={999}
                            precision={0}
                            placeholder="输入招聘人数"
                        />
                    )}
                </Form.Item>
                <Form.Item label="工作城市">
                    {getFieldDecorator('workCity', {
                        rules: [
                            {
                                required: true,
                                message: '请选择工作城市'
                            }
                        ]
                    })(
                        <Select mode="multiple" placeholder="选择工作城市" allowClear style={{ width: '55%' }}>
                            {cityList?.map(item => (
                                <Option value={item} key={item}>
                                    {item}
                                </Option>
                            ))}
                        </Select>
                    )}
                </Form.Item>
                <Form.Item label="工作性质">
                    {getFieldDecorator('workNature')(<Radio.Group>{renderRadios(dictObj?.jobNature)}</Radio.Group>)}
                </Form.Item>
            </Form>
            <BlockTitle title="岗位要求" style={{ marginBottom: 24 }} />
            <Form {...formItemLayout}>
                <Form.Item label="经验和学历">
                    <Row style={{ width: '55%' }}>
                        <Col span={12}>
                            {getFieldDecorator('workYears', {
                                rules: [
                                    {
                                        required: true,
                                        message: '工作年限不能为空'
                                    }
                                ]
                            })(
                                <Select placeholder="请选择工作年限" allowClear>
                                    {renderOptions(dictObj?.timeEmployedType)}
                                </Select>
                            )}
                        </Col>
                        <Col span={12}>
                            <Form.Item style={{ marginBottom: 0 }}>
                                <div style={{ height: 40, marginLeft: 20 }}>
                                    {getFieldDecorator('recruitDegree', {
                                        rules: [
                                            {
                                                required: true,
                                                message: '学历不能为空'
                                            }
                                        ]
                                    })(
                                        <Select placeholder="请选择学历" allowClear>
                                            {renderOptions(dictObj?.agreeType)}
                                        </Select>
                                    )}
                                </div>
                            </Form.Item>
                        </Col>
                    </Row>
                </Form.Item>
                <Form.Item label="性别">
                    {getFieldDecorator('recruitSex')(
                        <Radio.Group>{renderRadios(dictObj?.candidateSexType)}</Radio.Group>
                    )}
                </Form.Item>
                <Form.Item required label="薪资范围">
                    {renderSalaryForm()}
                </Form.Item>
                <Form.Item label="匹配职位">
                    <div>
                        {postData?.positionName || '--'}/{postData?.rankValue || '--'}
                    </div>
                </Form.Item>
                <Form.Item label="职位要求">
                    {getFieldDecorator('positionDuty', {
                        rules: [
                            {
                                required: true,
                                message: '职位要求不能为空'
                            }
                        ]
                    })(
                        <TextArea
                            placeholder="请输入职位要求"
                            autoSize={{ minRows: 6, maxRows: 9 }}
                            maxLength={2500}
                            style={{ width: '55%' }}
                        />
                    )}
                </Form.Item>
                <Form.Item label="岗位职责">
                    {getFieldDecorator('jobRequirement', {
                        rules: [
                            {
                                required: true,
                                message: '岗位职责不能为空'
                            }
                        ]
                    })(
                        <TextArea
                            placeholder="请输入岗位职责"
                            autoSize={{ minRows: 6, maxRows: 9 }}
                            maxLength={2500}
                            style={{ width: '55%' }}
                        />
                    )}
                </Form.Item>
                <Form.Item label="职位关键词">
                    {getFieldDecorator('positionTag')(
                        <Select
                            mode="tags"
                            style={{ width: '55%' }}
                            placeholder="请选择职位关键词"
                            allowClear
                            getPopupContainer={triggerNode => triggerNode.parentElement}
                            onFocus={handleTagChange}
                            onSearch={handleTagSearch}
                            tokenSeparators={[',']}
                            filterOption={false}
                        >
                            {tagList?.map(item => (
                                <Option value={item} key={item}>
                                    {item}
                                </Option>
                            ))}
                        </Select>
                    )}
                </Form.Item>
            </Form>
        </Card>
    );
};

export default Form.create({})(OfficialWebsitePreviewForm);
